package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.DishDto;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.entity.Dish;
import com.itheima.reggie.entity.DishFlavor;
import com.itheima.reggie.service.CategoryService;
import com.itheima.reggie.service.DishFlavorService;
import com.itheima.reggie.service.DishService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/dish")
@Slf4j
public class DishController {
    @Autowired
    private DishService dishService;

    @Autowired
    private DishFlavorService dishFlavorService;
    @Autowired
    CategoryService categoryService;

    @PostMapping
    @CacheEvict(value = "dishCache",allEntries = true)
    public R<String> save(@RequestBody DishDto dishDto) {
        dishService.saveWithFlavor(dishDto);
        return R.success("添加成功");
    }

    @GetMapping("/page")
    public R page(int page, int pageSize, String name) {
        Map map = new HashMap();
        Page<Dish> pageInfo = new Page<>(page, pageSize);

        LambdaQueryWrapper<Dish> qw = new LambdaQueryWrapper<>();

        qw.like(StringUtils.isNotEmpty(name), Dish::getName, name);

        qw.orderByDesc(Dish::getUpdateTime);

        dishService.page(pageInfo, qw);
        List<Dish> records = pageInfo.getRecords();
        long total = pageInfo.getTotal();
        map.put("total", total);

        ArrayList<DishDto> list = new ArrayList<>();

        for (Dish dish : records) {
            Long categoryId = dish.getCategoryId();
            Category byId = categoryService.getById(categoryId);
            DishDto dishDto = new DishDto();
            dishDto.setCategoryName(byId.getName());
            BeanUtils.copyProperties(dish, dishDto);
            list.add(dishDto);
        }

        map.put("records", list);

        return R.success(map);
    }

    @GetMapping("/{id}")
    public R<DishDto> getById(@PathVariable Long id) {
        DishDto byIdWithFlavor = dishService.getByIdWithFlavor(id);

        return R.success(byIdWithFlavor);
    }

    @PutMapping
   @CacheEvict(value = "dishCache",allEntries = true)
    public R<String> update(@RequestBody DishDto dishDto) {
        dishService.updateWithFlavor(dishDto);
        return R.success("修改菜品成功");
    }

    @DeleteMapping
    @CacheEvict(value = "dishCache",allEntries = true)
    public R<String> delete(@RequestParam List<Long> ids) {
        dishService.removeByIds(ids);
        return R.success("删除成功");
    }

    @PostMapping("/status/{status}")
    public R<String> status(@PathVariable int status, Long[] ids) {
        LambdaUpdateWrapper<Dish> qw = new LambdaUpdateWrapper<>();
        qw.set(Dish::getStatus, status);
        qw.in(Dish::getId, ids);
        dishService.update(qw);
        return R.success("操作成功");
    }
    //@GetMapping("/list")
    //public R<List<Dish>> getCategory(Dish dish){
    //    LambdaQueryWrapper<Dish> qw = new LambdaQueryWrapper<>();
    //
    //    qw.eq(dish.getCategoryId()!= null,Dish::getCategoryId,dish.getCategoryId());
    //   // qw.eq(Dish::getStatus,1);
    //    List<Dish> list = dishService.list(qw);
    //    return R.success(list);
    //
    //}

    @GetMapping("/list")
    @Cacheable(value = "dishCashe",key = "#dish.categoryId + '_' + #dish.status")
    public R<List<DishDto>> getCategory(Dish dish) {
        LambdaQueryWrapper<Dish> qw = new LambdaQueryWrapper<>();
        qw.eq(dish.getCategoryId() != null, Dish::getCategoryId, dish.getCategoryId());
        qw.eq(Dish::getStatus, 1);
        qw.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);
        List<Dish> list = dishService.list(qw);
        List<DishDto> list1 = list.stream().map((item) -> {
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(item, dishDto);
            Long categoryId = item.getCategoryId();
            Category category = categoryService.getById(categoryId);
            if (category != null) {
                dishDto.setCategoryName(category.getName());
            }
            LambdaQueryWrapper<DishFlavor> fqw = new LambdaQueryWrapper<>();
            Long id = item.getId();
            fqw.eq(DishFlavor::getDishId, id);
            List<DishFlavor> list2 = dishFlavorService.list(fqw);
            dishDto.setFlavors(list2);
            return dishDto;
        }).collect(Collectors.toList());

        return R.success(list1);

    }
}
